class Cip::Category < ApplicationRecord
  extend Unparsed

  has_many :pages

  has_attached_file :avatar, styles: { large: "500x500>", medium: "300x300>", thumb: "100x100#" }, preserve_files: true
  validates_attachment_content_type :avatar, :content_type => /\Aimage\/.*\Z/
  attr_accessor :_destroy_avatar
  before_validation do
    avatar.clear if _destroy_avatar == '1'
  end

  validates_presence_of :title

  FORWARDING_TYPES = { '当前分类': 'normal', '首个子分类': 'first_child', '空链接': 'blank', '页面链接': 'page', '分类链接': 'category', '外部链接': 'url' }
  validates_inclusion_of :forwarding_type, in: FORWARDING_TYPES.values

  def children_pages
    Cip::Page.where(category_id: children.pluck(:id) + [id])
  end

  serialize :metadata, JSON
  serialize :page_metadata_struct, JSON
  serialize :children_metadata_struct, JSON
  unparsed_attribute :page_metadata_struct
  unparsed_attribute :children_metadata_struct

  acts_as_tree name_column: :slug, order: :position

  def self.walk_tree tree = hash_tree, ancestors = [], &block
    tree.map do |category, children|
      result = block.call category, ancestors, children
      walk_tree children, ancestors + [category], &block if children.any?
      result
    end
  end

  def self.search_by id_or_slug
    if id_or_slug.is_a?(Integer) || id_or_slug =~ /\A\d+\z/
      where(id: id_or_slug).first
    else
      find_by(slug: id_or_slug)
    end
  end

  def self.search_by! id_or_slug
    if id_or_slug.is_a?(Integer) || id_or_slug =~ /\A\d+\z/
      find(id_or_slug)
    else
      find_by!(slug: id_or_slug)
    end
  end

  def url
    case forwarding_type
    when 'normal'
      Rails.application.routes.url_helpers.cip_category_path(id)
    when 'first_child'
      Rails.application.routes.url_helpers.cip_category_first_child_path(id)
    when 'page'
      Rails.application.routes.url_helpers.cip_page_path(forwarding_page_id)
    when 'category'
      Rails.application.routes.url_helpers.cip_category_path(forwarding_category_id)
    when 'url'
      forwarding_url
    when 'blank'
      '#'
    end
  end
end
